<?php

namespace app\controller\shop\plus;

use app\controller\shop\Controller;
use app\controller\shop\model\order\Order as OrderModel;
use app\controller\shop\model\plus\lottery\Lottery as LotteryModel;
use app\controller\shop\model\plus\lottery\Record as RecordModel;
use app\controller\shop\model\plus\lottery\LotteryPrize as LotteryPrizeModel;
use app\controller\shop\model\settings\Express as ExpressModel;
use app\controller\shop\model\user\Grade as GradeModel;

/**
 * 转盘控制器
 */
class Lottery extends Controller
{

    /**
     *修改
     */
    public function setting()
    {
        $model = new LotteryModel();
        if ($this->request->isGet()) {
            $data = $model->getLottery();
            $data['prize'] = $data ? LotteryPrizeModel::detail($data['lottery_id']) : [];
            // 会员等级列表
            $gradeList = GradeModel::getUsableList();
            return $this->renderSuccess('', compact('data', 'gradeList'));
        }
        if ($model->edit($this->postData())) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }

    /**
     * 转盘记录列表
     */
    public function record()
    {
        $model = new RecordModel();
        $list = $model->getList($this->postData());
        $lotteryType = $model->getLotteryType();
        return $this->renderSuccess('', compact('list', 'lotteryType'));
    }

    /**
     * 抽奖记录导出
     */
    public function export()
    {
        $model = new RecordModel();
        return $model->exportList($this->postData());
    }

    /**
     * 备注
     */
    public function remark()
    {
        $model = new RecordModel();
        if ($model->setRemark($this->postData())) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 查看物流
     */
    public function express($record_id)
    {
        $detail = RecordModel::detail($record_id);
        if (!$detail) {
            return $this->renderError('记录不存在');
        }
        // 订单信息
        $order = OrderModel::detail($detail['order_id'], ['express', 'address']);
        if (!$order || !$order['express_no']) {
            return $this->renderError('没有物流信息');
        }
        // 获取物流信息
        $model = $order['express'];
        $express = $model->dynamic($model['express_name'], $model['express_code'], $order['express_no'], $order['address']['phone']);
        if ($express === false) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess('', compact('express'));
    }
}